import axios from '@/plugins/axios/axios.js';
import { URL } from '@/common/index.js';
import { setCookies, getCookies, remove } from '@/utils/cookies.js';

// 默认的HTTP配置
const DEFAULT_OPTIONS = {
	// 所有请求的前缀
	prefix: process.env.BASE_API,
	// 默认的method
	method: 'POST',
	// 主要用来区分 @RequestBody 和 么有  还是有file类型的数据方式
	dataType: 'json', // 'JSON' - file
	// 接口是否不需要认证
	isAuth: true,
};

export const createAuthor = _ => {
	//发送ajax请求
	function ajax(userOption) {
		var defaultOption = {
			url: location.href,
			type: 'GET', //对大小不敏感
			success: function() {},
			error: function() {},
			data: null,
			timeout: 0,
		};
		var option = Object.assign({}, defaultOption, userOption);

		var xhr = new XMLHttpRequest();
		if (option.timeout > 0) {
			xhr.timeout = option.timeout;
		}

		//处理响应
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 4) {
				if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
					option.success(xhr.responseText);
				} else {
					option.error(xhr.status, xhr.statusText);
				}
			}
		};

		//处理超时
		xhr.ontimeout = function() {
			option.error(0, 'timeout');
		};

		//处理错误
		xhr.onerror = function() {
			options.error(0, 'error');
		};

		if (option.type.toUpperCase() === 'GET') {
			var url = formateUrl(option.url, option.data);
			//带上参数，是否异步发送请求
			xhr.open(option.type, url, true);
			xhr.send(null);
		} else {
			xhr.open(option.type, option.url, true);
			xhr.send(option.data);
		}
	}

	//格式化get请求的url
	function formateUrl(url, data) {
		//为参数间添加&符号，可以直接使用数组join处理
		var params = [];
		if (data instanceof FormData) {
			var entries = data.entries();
			for (var i of entries) {
				params.push(i[0] + '=' + i[1]);
			}
		} else {
			for (var i in data) {
				if (data.hasOwnProperty(i)) {
					params.push(i + '=' + data[i]);
				}
			}
		}

		if (params.length > 0) {
			if (url.indexOf('?') === -1) {
				url += '?';
			} else {
				url += '&';
			}
			url += params.join('&');
		}
		return url;
	}

	return new Promise((resolve, reject) => {
		ajax({
			url: '/yjz-oauth/oauth/token?grant_type=client_credentials&scope=all&client_id=web&client_secret=yjz2016',
			type: 'GET', //对大小不敏感
			success: result => {
				// 处理请求
				resolve({
					...JSON.parse(result),
				});
			},
			error: function() {},
			data: null,
			timeout: 0,
		});
	});
};

/**
 * HTTP 封装
 *  对于我们使用的http来说主要使用 3种 ，
 *
 *  1、  application/x-www-form-urlencoded
 *  2、  multipart/form-data
 *  3、  application/json
 *
 * @author guzhanghua
 * @export
 * @param {*} url
 * @param {*} params
 * @param {*} options
 * @returns
 */
export default function http(url, params, options) {
	// 配置
	const newOptions = {
		...DEFAULT_OPTIONS,
		...options,
	};

	let axiosOptions = {
		method: newOptions.method || 'POST',
		url: `${url}`,
		data: params,
		headers: {},
	};

	if (['POST', 'PUT', 'DELETE'].indexOf(newOptions.method) > -1) {
		if (newOptions.type === 'formdata') {
			axiosOptions.headers = {
				Accept: 'application/json',
				'Content-Type': 'application/x-www-form-urlencoded',
				...newOptions.headers,
			};
			axiosOptions.transformRequest = [
				function(data) {
					let ret = '';
					for (let it in data) {
						ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
					}
					return ret;
				},
			];
		} else if (newOptions.type === 'file') {
			axiosOptions.headers = {
				// Accept: 'application/json',
				'Content-Type': 'multipart/form-data',
				...newOptions.headers,
			};
		} else {
			axiosOptions.headers = {
				Accept: 'application/json',
				'Content-Type': 'application/json;charset=utf-8',
				...newOptions.headers,
			};
		}
	} else if (newOptions.method === 'GET') {
		// GET 类型 传输通过 params 属性
		axiosOptions.params = params;
		axiosOptions.headers = newOptions.headers
			? {
					...newOptions.headers,
			  }
			: {};
	}

	// 是否需要传入认证信息
	if (newOptions.isAuth) {
		// 在请求发送之前做一些处理
		const sid = getCookies('sid');
		// const sid = '0a15973b-ea05-4b7b-af50-192311ac39c1';
		if (sid && sid !== 'undefined') {
			// 让每个请求携带token-- ['sid']为自定义key 请根据实际情况自行修改
			axiosOptions.headers['sid'] = sid;
		}
	}
	// return axios(axiosOptions);
	return new Promise((resolve, reject) => {
		// 获取 auth

		let authVal = getCookies('auth_author');
		if (authVal) {
			axiosOptions.headers['Authorization'] = JSON.parse(authVal);
		} else {
			createAuthor()
				.then(res => {
					setCookies('auth_author', JSON.stringify('Bearer ' + res.access_token));
				})
				.catch(err => {
					this.$message.error('获取auth失败');
				});
			axiosOptions.headers['Authorization'] = JSON.parse(getCookies('auth_author'));
		}
		resolve(
			(_ => {
				return axios(axiosOptions);
			})()
		);
	});
}
